package cn.wolfcode.rocketmq._02_message_type;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

public class Producer {

    public static void main(String[] args) throws Exception{

        //创建生产者对象,并指定生产者组
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("wolfcode-producer");

        //设置超时时间
        defaultMQProducer.setSendMsgTimeout(10000);

        //设置名字服务的地址
        defaultMQProducer.setNamesrvAddr("127.0.0.1:9876");

        //启动生产者
        defaultMQProducer.start();

        CountDownLatch count = new CountDownLatch(100);

        for(int i=0;i<100;i++){
            //创建一个消息
            Message message = new Message("02_message_type","hello,RocketMQ!".getBytes("utf-8"));

            //发送消息
            defaultMQProducer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    count.countDown();
                    System.out.println("消息发送成功");
                    System.out.println(JSON.toJSONString(sendResult));
                }

                @Override
                public void onException(Throwable e) {
                    count.countDown();
                    System.out.println("消息发送失败");
                    System.out.println(JSON.toJSONString(e.getMessage()));
                }
            });
        }
        count.await();

        //关闭生产者连接
        defaultMQProducer.shutdown();


    }
}
